<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    
    
    <title>Nginx之upstream负载均衡 | 追光者的部落 | 种一棵树最好的时间是十年之前,其次是现在</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="keywords" content="Web服务器,Nginx">
    <link rel="shortcut icon" href="/img/favicon.ico">
    <link rel="stylesheet" href="/css/style.css?v=1.0.0">
    
    <script type="text/javascript">
        // Data Center
        var DC = {
            reward:	true,
            lv: JSON.parse('{"enable":false,"app_id":null,"app_key":null,"icon":true}'),
            v: JSON.parse('{"enable":true,"appid":"OCT05YTTqCrexJcyc5Ay0XXD-gzGzoHsz","appkey":"L6b0lDuLhBWOEUhEYmfA7g7C","notify":false,"verify":false,"placeholder":"suggest","avatar":"wavatar"}'),
            g: JSON.parse('{"enable":false,"lazy":true,"owner":"longmartin","repo":null,"oauth":{"client_id":null,"client_secret":null},"perPage":10}'),
            d: JSON.parse('{"app_id":null}')
        };
    </script>
    <script type="text/javascript">
        window.lazyScripts=[];
    </script>
    
</head>


<body>
    <div id="loading" class="active"></div>

    <aside id="menu" class="hide" >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap">
      
      <img src="/img/brand.jpg" class="brand-bg">
      
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">Martin Long</h5>
          <a href="mailto:1156341485@qq.com" title="1156341485@qq.com" class="mail">
            
              <span>1</span>
            
              <span>1</span>
            
              <span>5</span>
            
              <span>6</span>
            
              <span>3</span>
            
              <span>4</span>
            
              <span>1</span>
            
              <span>4</span>
            
              <span>8</span>
            
              <span>5</span>
            
              <span>@</span>
            
              <span>q</span>
            
              <span>q</span>
            
              <span>.</span>
            
              <span>c</span>
            
              <span>o</span>
            
              <span>m</span>
            
          </a>
        </hgroup>
        
        <ul class="menu-link">
          
              <li>
                <a href="https://github.com/longmartin" target="_blank">
                  <i class="icon icon-lg icon-github"></i>
                </a>
              </li>
            
        </ul>
        
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                HOME
              </a>
            </li>
        
            <li class="">
              <a href="/categories"  >
                <i class="icon icon-lg icon-th-list"></i>
                分类
              </a>
            </li>
        
            <li class="">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="">
              <a href="/archives"  >
                <i class="icon icon-lg icon-archives"></i>
                文档
              </a>
            </li>
        
            <li class="">
              <a href="https://github.com/longmartin" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="">
              <a href="https://www.jianshu.com/u/696184ca9e21" target="_blank" >
                <i class="icon icon-lg icon-link"></i>
                简书
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row clearfix">
        <a href="javascript:;" class="header-icon pull-left waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">
            <span>Nginx之upstream负载均衡</span>
            
        </div>
        
        <a href="javascript:;" id="site_search_btn" class="header-icon pull-right waves-effect waves-circle waves-light">
            <i class="icon icon-lg icon-search"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">
    <div class="container fade-scale">
        <h1 class="title">Nginx之upstream负载均衡</h1>
        <h5 class="subtitle">
            
                <time datetime="2018-06-17T09:22:50.000Z" itemprop="datePublished" class="page-time">
  2018-06-17
</time>


	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/server/">后台</a></li></ul>

            
        </h5>
        
    </div>
    

</header>

<div id="site_search">
    <div class="search-title clearfix">
        <span class="pull-left">
          <i class="icon icon-lg icon-search"></i>
        </span>
        <input type="text" id="local-search-input" name="q" results="0" placeholder="search my blog..." class="form-control pull-left"/>
        <a href="javascript:;" class="close pull-right waves-effect waves-circle waves-light">
          <i class="icon icon-lg icon-close"></i>
        </a>
    </div>
    <div id="local-search-result"></div>
</div>


<div class="container body-wrap">
    <article id="post-20180617-8"
  class="post-article article-type-post" itemprop="blogPost">
    <div class="post-card">
        <h1 class="post-card-title">Nginx之upstream负载均衡</h1>
        <div class="post-meta">
            <time class="post-time" title="2018-06-17 09:22:50" datetime="2018-06-17T09:22:50.000Z"  itemprop="datePublished">2018-06-17</time>

            
	<ul class="article-category-list"><li class="article-category-list-item"><a class="article-category-list-link" href="/categories/server/">后台</a></li></ul>



            

            
    <span class="leancloud-comment">
        <i class="icon icon-comment-o"></i>
        <a href="/server/20180617-8.html#comment">
            <span class="valine-comment-count" data-xid="/server/20180617-8.html"></span>
        </a>
    </span>



            
        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            
            <ul>
<li><h5 id="1-准备三台机器"><a href="#1-准备三台机器" class="headerlink" title="1. 准备三台机器"></a>1. 准备三台机器</h5>192.168.2.151        web服务器<br>192.168.2.152        web服务器<br>192.168.2.150        负载均衡服务器</li>
<li><h5 id="2-三台机器都配置-其中151-152作为web服务器，150作为负载均衡"><a href="#2-三台机器都配置-其中151-152作为web服务器，150作为负载均衡" class="headerlink" title="2. 三台机器都配置,其中151,152作为web服务器，150作为负载均衡"></a>2. 三台机器都配置,其中151,152作为web服务器，150作为负载均衡</h5></li>
</ul>
<p>ubuntu/debian<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">sudo apt update -y</span><br><span class="line">sudo apt install nginx</span><br></pre></td></tr></table></figure></p>
<p>centos<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">sudo yum install nginx -y</span><br></pre></td></tr></table></figure></p>
<p>安装成功后启动nginx</p>
<ul>
<li><h5 id="3-配置负载均衡服务器："><a href="#3-配置负载均衡服务器：" class="headerlink" title="3 配置负载均衡服务器："></a>3 配置负载均衡服务器：</h5><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">vim /etc/nginx/nginx.conf</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>内容如下：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">user  www-data;  </span><br><span class="line">worker_processes  1;  </span><br><span class="line">  </span><br><span class="line">error_log  /var/log/nginx/error.log warn;  </span><br><span class="line">pid        /var/run/nginx.pid;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">events &#123;  </span><br><span class="line">    worker_connections  1024;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">http &#123;  </span><br><span class="line">    include       /etc/nginx/mime.types;  </span><br><span class="line">    default_type  application/octet-stream;  </span><br><span class="line">  </span><br><span class="line">    log_format  main  &apos;$remote_addr - $remote_user [$time_local] &quot;$request&quot; &apos;  </span><br><span class="line">                      &apos;$status $body_bytes_sent &quot;$http_referer&quot; &apos;  </span><br><span class="line">                      &apos;&quot;$http_user_agent&quot; &quot;$http_x_forwarded_for&quot;&apos;;  </span><br><span class="line">  </span><br><span class="line">    access_log  /var/log/nginx/access.log  main;  </span><br><span class="line">  </span><br><span class="line">    sendfile        on;  </span><br><span class="line">    #tcp_nopush     on;  </span><br><span class="line">  </span><br><span class="line">    keepalive_timeout  65;  </span><br><span class="line">  </span><br><span class="line">    #gzip  on;  </span><br><span class="line">    upstream your.website.name &#123;  </span><br><span class="line">          server 192.168.2.151:80;  </span><br><span class="line">          server 192.168.2.152:80;  </span><br><span class="line">    &#125;  </span><br><span class="line">      </span><br><span class="line">  </span><br><span class="line">    server &#123;     </span><br><span class="line">        listen       80;</span><br><span class="line">        server_name your.website.name;       </span><br><span class="line">        charset utf-8;     </span><br><span class="line">        location / &#123;        </span><br><span class="line">            proxy_pass        http://your.website.name;     </span><br><span class="line">            proxy_set_header  X-Real-IP  $remote_addr;     </span><br><span class="line">            client_max_body_size  100m;  </span><br><span class="line">        &#125;     </span><br><span class="line">    </span><br><span class="line">    </span><br><span class="line">        location ~ ^/(WEB-INF)/ &#123;      </span><br><span class="line">               deny all;      </span><br><span class="line">        &#125;      </span><br><span class="line">    </span><br><span class="line">        error_page   500 502 503 504  /50x.html;     </span><br><span class="line">        location = /50x.html &#123;     </span><br><span class="line">            root   /var/www/html/;     </span><br><span class="line">        &#125;     </span><br><span class="line">    &#125;     </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>浏览器打开192.168.2.150，如果151、152交替显示则表明试验成功。</p>
<ul>
<li><h5 id="4-其他的功能扩展"><a href="#4-其他的功能扩展" class="headerlink" title="4. 其他的功能扩展"></a>4. 其他的功能扩展</h5>(1)、轮询（默认）<br>每个请求按时间顺序逐一分配到不同的后端服务器，如果后端服务器down掉，能自动剔除。<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">upstream your.website.name &#123;  </span><br><span class="line">      server 192.168.2.151:80;  </span><br><span class="line">      server 192.168.2.152:80;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p>(2)、weight<br>指定轮询几率，weight和访问比率成正比，用于后端服务器性能不均的情况。例如：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">upstream your.website.name &#123;</span><br><span class="line">     server 192.168.2.151 weight=5 max_fails=3 fail_timeout=20s;;</span><br><span class="line">     server 192.168.2.152 weight=10 max_fails=3 fail_timeout=20s;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>(3)、ip_hash<br>每个请求按访问ip的hash结果分配，这样每个访客固定访问一个后端服务器，可以解决session的问题。例如：<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">upstream your.website.name &#123;</span><br><span class="line">     ip_hash;</span><br><span class="line">     server 192.168.2.151:80;</span><br><span class="line">     server 192.168.2.152:80;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>(4)、fair（需要安装第三方库upstream-fair支持）<br>按后端服务器的响应时间来分配请求，响应时间短的优先分配。<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">upstream your.website.name &#123;</span><br><span class="line">     server 192.168.2.151:80;</span><br><span class="line">     server 192.168.2.152:80;</span><br><span class="line">     fair;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>(5)、url_hash（需要安装第三方库Nginx_upstream_hash支持）</p>
<p>按访问url的hash结果来分配请求，使每个url定向到同一个后端服务器，后端服务器为缓存时比较有效。<br>例：在upstream中加入hash语句，server语句中不能写入weight等其他的参数，hash_method是使用的hash算法<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">upstream your.website.name &#123;</span><br><span class="line">     server 192.168.2.151:80;</span><br><span class="line">     server 192.168.2.152:80;</span><br><span class="line">      hash $request_uri;</span><br><span class="line">      hash_method crc32;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>(6)、建议<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">upstream your.website.name&#123; #定义负载均衡设备的Ip及设备状态</span><br><span class="line">      ip_hash;</span><br><span class="line">      server 127.0.0.1:8000 down;</span><br><span class="line">      server 127.0.0.1:8080 weight=2;</span><br><span class="line">      server 127.0.0.1:6801;</span><br><span class="line">      server 127.0.0.1:6802 backup;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>解释：<br>1.down 表示单前的server暂时不参与负载<br>2.weight 默认为1.weight越大，负载的权重就越大。<br>3.max_fails ：允许请求失败的次数默认为1.当超过最大次数时，返回proxy_next_upstream 模块定义的错误<br>4.fail_timeout:max_fails次失败后，暂停的时间。<br>5.backup： 其它所有的非backup机器down或者忙的时候，请求backup机器。所以这台机器压力会最轻。</p>
<ul>
<li><h4 id="5-总结"><a href="#5-总结" class="headerlink" title="5.总结"></a>5.总结</h4>实际上，我们可以部署时，设置服务器作为backup备份，设置服务器暂时不开启(down),必要活动时在开启，跟进服务器的不同配置设置不同的比重(weight),还可以设置默认同一个ip自动进同一个服务器，这样保证session的一致性。</li>
</ul>

        </div>
        
<blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    Last updated: <time datetime="2018-06-17T01:25:03.651Z" itemprop="dateUpdated">2018-06-17 01:25:03</time>
</span><br>


        
        转载注明出处，原文地址：<a href="/server/20180617-8.html" target="_blank" rel="external">http://blog.inbelieve.top/server/20180617-8.html</a>
        
    </div>
    <footer>
        <a href="http://blog.inbelieve.top">
            <img src="/img/avatar.jpg" alt="Martin Long">
            Martin Long
        </a>
    </footer>
</blockquote>

        
            <div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>

            
        
        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/nginx/">Nginx</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/webserver/">Web服务器</a></li></ul>

            <div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://blog.inbelieve.top/server/20180617-8.html&title=《Nginx之upstream负载均衡》 — 追光者的部落&source=有些鸟儿天生是没办法被关在笼子里的,因为他的每一片羽毛都闪耀着自由的光辉" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>

        </div>
        
            
    <div id="comment"></div>



        
    </div>
    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="prev">
      <a href="/server/20180617-9.html" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">nginx配置允许跨域</h4>
      </a>
    </div>
  

  
    <div class="next">
      <a href="/server/20180617-7.html" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">Nginx之alias与root</h4>
      </a>
    </div>
  
</nav>


    
    
        <aside class="post-widget">
            <nav class="post-toc-wrap" id="post-toc">
                <strong>目录</strong>
                <ol class="post-toc"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#5-总结"><span class="post-toc-number">1.</span> <span class="post-toc-text">5.总结</span></a></li></ol>
            </nav>
            <div class="toc-bar"><div>
        </aside>
    
</article>

    <div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
            请作者喝杯咖啡
    </h3>
    <div class="reward-content">
        
        <div class="reward-code">
            <img id="rewardCode" src="/img/wechat.jpg" alt="打赏二维码">
        </div>
        
        <label class="reward-toggle">
            <input id="rewardToggle" type="checkbox" class="reward-toggle-check"
                data-wechat="/img/wechat.jpg" data-alipay="/img/alipay.jpg">
            <div class="reward-toggle-ctrol">
                <span class="reward-toggle-item wechat">微信</span>
                <span class="reward-toggle-label"></span>
                <span class="reward-toggle-item alipay">支付宝</span>
            </div>
        </label>
        
    </div>
</div>

    
</div>

        <footer class="footer">
    
    <div class="bottom">
        <p>
            <span>
                Martin Long &copy; 2017 - 2018
            </span>
        		
           	
            
            
            <span>
	            Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/codefine/hexo-theme-mellow" target="_blank">book</a>
            </span>
            
            
            
        </p>
    </div>
</footer>

    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://blog.inbelieve.top/server/20180617-8.html&title=《Nginx之upstream负载均衡》 — 追光者的部落&source=有些鸟儿天生是没办法被关在笼子里的,因为他的每一片羽毛都闪耀着自由的光辉" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>


    
    <!-- main-js -->
<script type="text/javascript" src="//cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript" src="/js/plugins/fastclick.js?v=1.0.0"></script>

<script type="text/javascript" src="https://cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>

<script type="text/javascript" src="/js/method.js?v=1.0.0"></script>
<script type="text/javascript" src="/js/blog.js?v=1.0.0"></script>

<!-- third-party -->





<script type="text/javascript" src="/js/plugins/local_search.js?v=1.0.0"></script>
<script type="text/javascript">
	var search_path = "search.xml";
	if (search_path.length === 0) {
		search_path = "search.xml";
	}
	var path = "/" + search_path;
	searchFunc(path, "local-search-input", "local-search-result");
</script>



    
        <script type="text/javascript" src="https://cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script type="text/javascript" src="//unpkg.com/valine/dist/Valine.min.js"></script>
<script type="text/javascript" src="/js/plugins/valine.js?v=1.0.0"></script>
    
    







    <script>
    (function() {
        var OriginTitile = document.title, titleTime;
        document.addEventListener('visibilitychange', function() {
            if (document.hidden) {
                document.title = 'leaving！';
                clearTimeout(titleTime);
            } else {
                document.title = 'welcome!';
                titleTime = setTimeout(function() {
                    document.title = OriginTitile;
                },2000);
            }
        });
    })();
</script>




    
</body>
</html>
